<template>
  <div class="app-container">
    <header class="app-header">
      <h1 class="app-title">随机抽吃啥</h1>
      <p class="app-subtitle">今天吃什么？让命运来决定！</p>
    </header>
    
    <main class="app-main">
      <!-- 结果展示区域 -->
      <section class="result-section">
        <ResultDisplay
          :current-food="currentFood"
          :is-rolling="isRolling"
          :rolling-foods="rollingFoods"
        />
      </section>
      
      <!-- 按钮区域 -->
      <section class="button-section">
        <RandomButton
          :is-rotating="isRolling"
          button-text="随机抽吃啥"
          @randomize="handleRandomize"
        />
      </section>
      
      <!-- 筛选和历史区域 -->
      <section class="filter-history-section">
        <CategoryFilter
          :selected-category="selectedCategory"
          @category-change="handleCategoryChange"
        />
        <HistoryDisplay :history="history" />
      </section>
      
      <!-- 食物列表和自定义区域 -->
      <section class="list-custom-section">
        <div class="food-list-wrapper">
          <FoodList
            :foods="allFoods"
            :selected-food="currentFood"
            :filter-category="selectedCategory"
          />
        </div>
        <div class="custom-manager-wrapper">
          <CustomFoodManager
            :custom-foods="customFoods"
            @add-food="handleAddFood"
            @delete-food="handleDeleteFood"
          />
        </div>
      </section>
    </main>
  </div>
</template>

<script>
import FoodList from './components/FoodList.vue';
import RandomButton from './components/RandomButton.vue';
import ResultDisplay from './components/ResultDisplay.vue';
import CategoryFilter from './components/CategoryFilter.vue';
import HistoryDisplay from './components/HistoryDisplay.vue';
import CustomFoodManager from './components/CustomFoodManager.vue';
import { foodData } from './data/foodData.js';

export default {
  name: 'App',
  components: {
    FoodList,
    RandomButton,
    ResultDisplay,
    CategoryFilter,
    HistoryDisplay,
    CustomFoodManager
  },
  data() {
    return {
      // 基础食物数据
      baseFoods: foodData,
      // 自定义食物数据
      customFoods: [],
      // 当前选中的食物
      currentFood: null,
      // 是否正在抽取动画中
      isRolling: false,
      // 滚动展示的食物列表
      rollingFoods: [],
      // 选中的分类
      selectedCategory: 'all',
      // 历史记录
      history: []
    };
  },
  computed: {
    // 合并基础食物和自定义食物
    allFoods() {
      return [...this.baseFoods, ...this.customFoods];
    },
    // 根据分类筛选的食物列表
    filteredFoods() {
      if (this.selectedCategory === 'all') {
        return this.allFoods;
      }
      return this.allFoods.filter(food => food.category === this.selectedCategory);
    }
  },
  created() {
    // 尝试从localStorage加载自定义食物和历史记录
    this.loadCustomFoods();
    this.loadHistory();
  },
  methods: {
    // 处理随机抽取
    async handleRandomize() {
      if (this.isRolling || this.filteredFoods.length === 0) {
        return;
      }
      
      this.isRolling = true;
      
      // 准备滚动食物列表（随机选择30个食物进行滚动）
      this.prepareRollingFoods();
      
      // 模拟滚动动画效果（持续2-3秒）
      const duration = Math.floor(Math.random() * 1000) + 2000;
      
      await new Promise(resolve => setTimeout(resolve, duration));
      
      // 随机选择最终结果
      const randomIndex = Math.floor(Math.random() * this.filteredFoods.length);
      this.currentFood = this.filteredFoods[randomIndex];
      
      // 添加到历史记录
      this.addToHistory(this.currentFood);
      
      // 停止滚动动画
      setTimeout(() => {
        this.isRolling = false;
      }, 100);
    },
    
    // 准备滚动食物列表
    prepareRollingFoods() {
      const tempFoods = [];
      const foodCount = Math.min(30, this.filteredFoods.length);
      
      // 随机选择食物
      const shuffled = [...this.filteredFoods].sort(() => 0.5 - Math.random());
      tempFoods.push(...shuffled.slice(0, foodCount));
      
      // 如果食物不够，重复添加一些
      while (tempFoods.length < 30) {
        const randomIndex = Math.floor(Math.random() * this.filteredFoods.length);
        tempFoods.push(this.filteredFoods[randomIndex]);
      }
      
      this.rollingFoods = tempFoods;
    },
    
    // 处理分类变化
    handleCategoryChange(category) {
      this.selectedCategory = category;
    },
    
    // 处理添加自定义食物
    handleAddFood(food) {
      this.customFoods.push(food);
      this.saveCustomFoods();
    },
    
    // 处理删除自定义食物
    handleDeleteFood(id) {
      this.customFoods = this.customFoods.filter(food => food.id !== id);
      this.saveCustomFoods();
    },
    
    // 添加到历史记录
    addToHistory(food) {
      const historyItem = {
        ...food,
        timestamp: Date.now()
      };
      
      // 添加到历史记录开头
      this.history.unshift(historyItem);
      
      // 只保留最近5条
      if (this.history.length > 5) {
        this.history = this.history.slice(0, 5);
      }
      
      this.saveHistory();
    },
    
    // 保存自定义食物到localStorage
    saveCustomFoods() {
      try {
        localStorage.setItem('customFoods', JSON.stringify(this.customFoods));
      } catch (e) {
        console.error('保存自定义食物失败:', e);
      }
    },
    
    // 从localStorage加载自定义食物
    loadCustomFoods() {
      try {
        const saved = localStorage.getItem('customFoods');
        if (saved) {
          this.customFoods = JSON.parse(saved);
        }
      } catch (e) {
        console.error('加载自定义食物失败:', e);
      }
    },
    
    // 保存历史记录到localStorage
    saveHistory() {
      try {
        localStorage.setItem('foodHistory', JSON.stringify(this.history));
      } catch (e) {
        console.error('保存历史记录失败:', e);
      }
    },
    
    // 从localStorage加载历史记录
    loadHistory() {
      try {
        const saved = localStorage.getItem('foodHistory');
        if (saved) {
          this.history = JSON.parse(saved);
        }
      } catch (e) {
        console.error('加载历史记录失败:', e);
      }
    }
  }
}
</script>

<style>
/* 全局样式重置 */
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

body {
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen',
    'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue',
    sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  min-height: 100vh;
  padding: 20px;
}

#app {
  max-width: 1200px;
  margin: 0 auto;
}
</style>

<style scoped>
.app-container {
  width: 100%;
}

.app-header {
  text-align: center;
  margin-bottom: 40px;
  padding-top: 20px;
}

.app-title {
  font-size: 40px;
  font-weight: 700;
  color: #333;
  margin-bottom: 10px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

.app-subtitle {
  font-size: 18px;
  color: #666;
}

.app-main {
  display: grid;
  grid-template-columns: 1fr 1fr;
  grid-template-rows: auto auto 1fr;
  gap: 24px;
}

.result-section {
  grid-column: 1 / -1;
}

.button-section {
  grid-column: 1 / -1;
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 20px 0;
}

.filter-history-section {
  grid-column: 1 / 2;
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.list-custom-section {
  grid-column: 2 / -1;
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.food-list-wrapper,
.custom-manager-wrapper {
  flex: 1;
}

/* 响应式设计 */
@media (max-width: 1024px) {
  .app-main {
    grid-template-columns: 1fr;
  }
  
  .filter-history-section,
  .list-custom-section {
    grid-column: 1 / -1;
  }
  
  .list-custom-section {
    flex-direction: row;
    gap: 20px;
  }
  
  .food-list-wrapper,
  .custom-manager-wrapper {
    flex: 1;
  }
}

@media (max-width: 768px) {
  body {
    padding: 16px;
  }
  
  .app-header {
    margin-bottom: 30px;
    padding-top: 16px;
  }
  
  .app-title {
    font-size: 32px;
  }
  
  .app-subtitle {
    font-size: 16px;
  }
  
  .app-main {
    gap: 20px;
  }
  
  .list-custom-section {
    flex-direction: column;
  }
}

@media (max-width: 480px) {
  body {
    padding: 12px;
  }
  
  .app-header {
    margin-bottom: 24px;
    padding-top: 12px;
  }
  
  .app-title {
    font-size: 28px;
  }
  
  .app-subtitle {
    font-size: 14px;
  }
  
  .app-main {
    gap: 16px;
  }
}
</style>
